/*
 * Title:        ConfigDecoratorMapper
 * Description:
 *
 * This software is published under the terms of the OpenSymphony Software
 * License version 1.1, of which a copy has been included with this
 * distribution in the LICENSE.txt file.
 */

package com.opensymphony.module.sitemesh.mapper;

import com.opensymphony.module.sitemesh.Config;
import com.opensymphony.module.sitemesh.Decorator;
import com.opensymphony.module.sitemesh.DecoratorMapper;
import com.opensymphony.module.sitemesh.Page;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;

import com.et114.components.sitemesh.SiteMeshConst;

//import org.springframework.util.Assert;

/**
 * Default implementation of DecoratorMapper. Reads decorators and
 * mappings from the <code>config</code> property (default '/WEB-INF/decorators.xml').
 *
 * @author <a href="joe@truemesh.com">Joe Walnes</a>
 * @author <a href="mcannon@internet.com">Mike Cannon-Brookes</a>
 * @version $Revision: 1.4 $
 *
 * @see com.opensymphony.module.sitemesh.DecoratorMapper
 * @see com.opensymphony.module.sitemesh.mapper.DefaultDecorator
 * @see com.opensymphony.module.sitemesh.mapper.ConfigLoader
 */
public class ConfigDecoratorMapper extends AbstractDecoratorMapper {
	protected Log logger = LogFactory.getLog( this.getClass() );
    private ConfigLoader configLoader = null;

    /** Create new ConfigLoader using '/WEB-INF/decorators.xml' file. */
    public void init(Config config, Properties properties, DecoratorMapper parent) throws InstantiationException {
        super.init(config, properties, parent);
        try {
            String fileName = properties.getProperty("config", "/WEB-INF/decorators.xml");
            configLoader = new ConfigLoader(fileName, config);
        }
        catch (Exception e) {
            throw new InstantiationException(e.toString());
        }
    }

    /** Retrieve {@link com.opensymphony.module.sitemesh.Decorator} based on 'pattern' tag. */
    public Decorator getDecorator(HttpServletRequest request, Page page) {
        String thisPath = request.getServletPath();

        // getServletPath() returns null unless the mapping corresponds to a servlet
        if (thisPath == null) {
            String requestURI = request.getRequestURI();
            if (request.getPathInfo() != null) {
                // strip the pathInfo from the requestURI
                thisPath = requestURI.substring(0, requestURI.indexOf(request.getPathInfo()));
            }
            else {
                thisPath = requestURI;
            }
        }
        
        //guanhw 
          StringBuffer sb = new StringBuffer() ;
          String method = request.getParameter ( "method" ) ;
          if ( method != null && !"".equals ( method ) ) {
        	  String value = request.getParameter (  "method"  ) ;
        	  sb.append( "method"  ).append( "=" ).append( value ) ;
          }
          
        
	      java.util.Enumeration eu = request.getParameterNames(); 
	      if ( eu != null  ) {
		      while( eu.hasMoreElements() ) {
			        String key = ( String  )eu.nextElement();  
			        if ( !"method".equals ( key ) ) {
				        String value = request.getParameter( key ) ;
				        sb.append ( "&" ).append( key  ).append( "=" ).append( value );	
				        break ; 
			        }
			      }
	      }
	      
	     
	      if ( sb.length ( ) > 0  ) {
	    	  thisPath = thisPath + "?" + sb.toString() ;
	      }
	      
	      
	    //logger.info ( "sitemesh 请求url..." + thisPath ) ;
        String name = null;
        try {
        
        	String decorat = request.getParameter ( SiteMeshConst.SITEMESH_DECORT ) ; 
        	//加校验
        	if ( decorat == null || (  decorat != null && ( Integer.valueOf ( decorat ).byteValue ( )  ) == SiteMeshConst.isDecorat ) ) {
        		name = configLoader.getMappedName( thisPath );
        	}
        	
            //logger.info ( "sitemesh 请求url..." +  thisPath + "修饰文件" + name ) ;           
        }
        catch (ServletException e) {
            e.printStackTrace();
        }

        Decorator result = getNamedDecorator(request, name);
        return result == null ? super.getDecorator(request, page) : result;
    }

    /** Retrieve Decorator named in 'name' attribute. Checks the role if specified. */
    public Decorator getNamedDecorator(HttpServletRequest request, String name) {
        Decorator result = null;
        try {
            result = configLoader.getDecoratorByName(name);
        }
        catch (ServletException e) {
            e.printStackTrace();
        }

        if (result == null || (result.getRole() != null && !request.isUserInRole(result.getRole()))) {
            // if the result is null or the user is not in the role
            return super.getNamedDecorator(request, name);
        }
        else {
            return result;
        }
    }
}
